package com.shop.cloud.common.im.util;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.shop.cloud.common.im.config.IMConfigProperties;
import com.shop.cloud.common.im.entity.LoginReq;
import com.shop.cloud.common.im.entity.RegisterReq;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

/**
 * IM工具
 */
@Slf4j
@Configuration
@AllArgsConstructor
public class IMUtils {

	private final IMConfigProperties iMConfigProperties;

	/**
	 * 登录
	 * @return
	 */
	public JSONObject login(LoginReq loginReq){
		loginReq.setSecret(iMConfigProperties.getSecret());
		String imBody = HttpRequest
				.post("https://"+iMConfigProperties.getUrl()+"/api/auth/user_token")
				.body(JSONUtil.toJsonStr(loginReq))
				.execute().body();
		JSONObject jSONObject = JSONUtil.parseObj(imBody);
		int errCode = jSONObject.getInt("errCode");
		if(errCode == 0){
			//将IM服务器地址传给前端
			jSONObject.putOnce("url", iMConfigProperties.getUrl());
		}
		return jSONObject;
	}

	/**
	 * 注册
	 * @return
	 */
	public JSONObject register(RegisterReq registerReq){
		registerReq.setSecret(iMConfigProperties.getSecret());
		String imBody = HttpRequest
				.post("https://"+iMConfigProperties.getUrl()+"/api/auth/user_register")
				.body(JSONUtil.toJsonStr(registerReq))
				.execute().body();
		JSONObject jSONObject = JSONUtil.parseObj(imBody);
		return jSONObject;
	}
}
